package com.proxy.customer;

import java.io.*;

/**
 * @author: AaronChun
 * @create: 2019-03-25 10:56
 * @description:
 **/
public class CustomerClassLoader extends ClassLoader {


    public CustomerClassLoader(ClassLoader parent) {
        super(parent);
    }

    private Class clazz;

    public CustomerClassLoader(Class clazz) {
        this.clazz = clazz;
    }


    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String path = clazz.getInterfaces()[0].getResource("").getPath();

        File ClassFile = new File(path + name.substring(name.lastIndexOf(".") + 1) + ".class");


        if (ClassFile.exists()) {
            FileInputStream fis = null;
            ByteArrayOutputStream baos = null;

            try {
                fis = new FileInputStream(ClassFile);
                baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[2048];
                int length = 0;
                while ((length = fis.read(buffer)) != -1) {
                    baos.write(buffer, 0, length);
                }

                return defineClass(name, baos.toByteArray(), 0, baos.size());


            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                ClassFile.delete();
            }


        }
        return null;

    }
}
